package com.zzg.controller;

import java.lang.reflect.UndeclaredThrowableException;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zzg.base.response.BaseResponse;
import com.zzg.common.exception.CommonException;
import com.zzg.consts.Constants;
import com.zzg.enums.ResponseStatusEnum;
import com.zzg.util.result.ResultUtil;

import cn.hutool.core.util.ObjectUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

@Api(value = "异常",description = "全局异常处理")
@ControllerAdvice  //@RestControllerAdvice 该注解将异常以json格式输出
@Slf4j
public class ExceptionHandleController {
	@ExceptionHandler(value = Exception.class)
    @ResponseBody
    public BaseResponse handleHope(Throwable e){

        if (e instanceof CommonException){
            log.error(e.getMessage());
            return ResultUtil.error(e.getMessage());
        }

        if (e instanceof UndeclaredThrowableException) {
            e=((UndeclaredThrowableException) e).getUndeclaredThrowable();
        }

        ResponseStatusEnum statusEnum =ResponseStatusEnum.get(e.getMessage());

        if (ObjectUtil.isNotNull(statusEnum)){
            log.error(statusEnum.getMessage());
            return ResultUtil.error(statusEnum.getCode(),statusEnum.getMessage());
        }

        return ResultUtil.error(Constants.DEFAULT_ERROR_CODE,ResponseStatusEnum.ERROR.getMessage());
    }

    @ExceptionHandler(AuthorizationException.class)
    public String handleAuth(HttpServletRequest request) {
        request.setAttribute("javax.servlet.error.status_code",ResponseStatusEnum.FORBIDDEN.getCode());
        return "forward:/error1";
    }
}
